package com.base.kotlin.mvvm

import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.OnLifecycleEvent
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import com.base.delegate.weak
import io.reactivex.disposables.Disposable

/**
 * @author zhouzechao
 * 公共的P层，监听好Lifecycle解绑view以及设置了弱引用的属性
 * mDisposables为rxjava的Disposable，通过销毁结束请求
 * getViewModel()链接viewModel层
 */
abstract class BaseVmPresenter<V : IView> : LifecycleObserver {

    protected var mView: V? by weak()
    protected var mDisposables = LinkedHashSet<Disposable>()

    /**
     * 绑定view，一般在初始化中调用该方法
     *
     * @param view view
     */
    fun <P : BaseVmPresenter<*>> attachView(view: V): P {
        mView = view
        onCreate()
        return this as P
    }

    abstract fun onCreate()

    fun <T : BaseViewModel<*>> getViewModel(context: Context, viewModel: Class<T>): T? {
        var mViewModel: T? = null
        try {
            if (context is Fragment) {
                mViewModel = ViewModelProviders.of(context as Fragment).get(viewModel).initModel()
            } else if (context is FragmentActivity) {
                mViewModel = ViewModelProviders.of(context).get(viewModel).initModel()
            }
        } catch (e: Exception) {

        }
        return mViewModel
    }

    private fun detachView() {
        mView = null
    }

    /**
     * View是否绑定
     *
     * @return
     */
    fun isViewAttached(): Boolean {
        return mView != null
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    open fun onDestroy() {
        for (disposable in mDisposables) {
            disposable.dispose()
        }
        detachView()
    }
}